﻿using Api;
using Events.Dto;
using Furion.EventBus;

namespace Events;

/// <summary>
/// 订单eventbus
/// </summary>
public class OrderEvent : IEventSubscriber, ISingleton
{
    private readonly ISqlSugarClient db;

    private readonly Common com;
    private readonly WechatAppletApi wechat;


    /// <summary>
    /// 订单事件
    /// </summary>
    /// <param name="db"></param>
    /// <param name="com"></param>
    /// <param name="wechat"></param>
    public OrderEvent(ISqlSugarClient db, Common com, WechatAppletApi wechat)
    {
        this.db = db;
        this.com = com;
        this.wechat = wechat;
    }

    /// <summary>
    /// 修改订单状态为成功
    /// </summary>
    /// <param name="ctx"></param>
    /// <returns></returns>
    [EventSubscribe("OrderComplete")]
    public async Task ChangeState(EventHandlerContext ctx)
    {
        try
        {
            var input = (Dto.OrderComplete)ctx.Source.Payload;

            var order = await com.GetOrder(input.OrderNo);

            if (order.PayStatus != Entity.PayStatus.未支付) return;

            order.PayStatus = Entity.PayStatus.已支付;

            order.ThreeOrderNo = input.ThreeOrderNo;

            order.PayType = input.PayType;

            await db.Updateable(order).ExecuteCommandHasChangeAsync();

        }
        catch (Exception e)
        {
            Console.WriteLine("Event:ordercomplete:修改订单状态:" + e.Message);
        }
    }


    /// <summary>
    /// 小程序下单发货
    /// </summary>
    /// <param name="ctx"></param>
    /// <returns></returns>
    [EventSubscribe("SubWechatOrder")]
    public async Task SubWechatOrder(EventHandlerContext ctx)
    {
        var data = (SubWechatOrderDto)ctx.Source.Payload;

        var order = await com.GetOrder(data.OrderNo);

        string goodsInfo = "";

        if (order.OrderType == Entity.OrderType.拼团返利) goodsInfo = "参与拼团活动";
        
        if (order.OrderType == Entity.OrderType.排队免单) goodsInfo = "参与零元购活动";
        
        if (order.OrderType == Entity.OrderType.每月免费商品) return;
       
        await wechat.SendOrder(data.OrderNo, goodsInfo, data.OpenId, 3);
    }




}
